/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xmlProject.controller;

import com.xmlProject.ultils.DBUltils;
import com.xmlProject.ultils.XMLUltils;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sample.accounts.Product;

/**
 *
 * @author Admin
 */
public class CustomerController extends HttpServlet {

    private final String xmlProductsFile = "WEB-INF/products.xml";
    private static Product product = null;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String appPath = getServletContext().getRealPath("/");

        try {

            String action = request.getParameter("btAction");
            if (action.equals("Login")) {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                String result = DBUltils.checkLogin(username, password);
                if (result != null) {
                    session.setAttribute("USER", result);
                }
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                rd.forward(request, response);
                return;
            } else if (action.equals("Search")) {
                String txtName = request.getParameter("txtName");
                request.setAttribute("SKEY", txtName);
                RequestDispatcher rd = request.getRequestDispatcher("searchResult.jsp");
                rd.forward(request, response);
                return;
            } else if (action.equals("ViewProductDetail")) {
                int id = Integer.parseInt(request.getParameter("txtId"));
                String xmlFileName = appPath + "WEB-INF/products.xml";
                Document xmlDoc = XMLUltils.parseDOMFromFile(xmlFileName);
                getProductByID(xmlDoc, request.getParameter("txtId"));
                if (product!=null){
                    request.setAttribute("DETAIL", product);
                    product = null;
                }
                RequestDispatcher rd = request.getRequestDispatcher("productDetail.jsp");
                rd.forward(request, response);
                return;
            }
        } finally {
            out.close();
        }
    }
    private static void getProductByID(Node currentNode, String id) {
        boolean productFound = false;
        if (currentNode == null) {
            return;
        } else if (currentNode.getNodeName().equals("product")) {
            NodeList pChilds = currentNode.getChildNodes();
            int productId = 0;
            String productName = "";
            String description = "";
            float price = 0;
            String manufacturer = "";
            String category = "";
            for (int i = 0; i < pChilds.getLength(); i++) {
                Node pTmp = pChilds.item(i);
                if (pTmp.getNodeName().equals("price")) {
                    price = Float.parseFloat(pTmp.getTextContent().trim());
                } else if (pTmp.getNodeName().equals("description")) {
                    description = pTmp.getTextContent().trim();
                } else if (pTmp.getNodeName().equals("category")) {
                    category = pTmp.getTextContent().trim();
                }else if (pTmp.getNodeName().equals("manufacturer")) {
                    manufacturer = pTmp.getTextContent().trim();
                } else if (pTmp.getNodeName().equals("productName")) {
                    productName = pTmp.getTextContent().trim();
                } else if (pTmp.getNodeName().equals("id")) {
                    productId = Integer.parseInt(pTmp.getTextContent().trim());
                    if (pTmp.getTextContent().trim().equals(id)) {
                        productFound = true;
                    }
                }
            }
            if (productFound) {
                product = new Product();
                product.setProductName(productName);
                product.setManufacturer(manufacturer);
                product.setPrice(price);
                product.setDescription(description);
                product.setCategory(category);
            }

        }
        for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) {
            getProductByID(currentNode.getChildNodes().item(i), id);
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
